import { postWhthGetUser } from '@/services/user';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'user',
  state: {
    currentUser: {},
  },

  effects: {
    *fetchCurrent({ payload }, { call, put }) {
      const response = yield call(postWhthGetUser, payload);
      console.log(response, '--------response');
      window.localStorage.setItem('robotId', response.robotId);
      window.localStorage.setItem('uid', response.uid);
      window.localStorage.setItem('robotName', response.robotName ? response.robotName : '');
      if (response.status !== undefined && !response.status) {
        yield put(routerRedux.replace('/user/login'));
      } else {
        yield put({
          type: 'saveCurrentUser',
          payload: response,
        });
      }
    },
  },
  subscriptions: {
    setup({ dispatch }) {
      const data = JSON.parse(localStorage.getItem('currentUser'));
      if (!data) {
        dispatch({
          type: 'saveCurrentUser',
          payload: {},
        });
      } else {
        dispatch({
          type: 'saveCurrentUser',
          payload: data,
        });
      }
    },
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/user/login') {
          dispatch({
            type: 'saveCurrentUser',
            payload: {},
          });
        }
      });
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
